 //
//  DSSHScanQRcode.m
//  DSSH
//
//  Created by Fuhao on 16/4/20.
//  Copyright © 2016年 lcy. All rights reserved.
//

#import "DSSHScanQRcode.h"
#import "ScanQRcodev.h"

#define  SCANZ 250

static SystemSoundID shake_sound_male_id = 0;
@interface DSSHScanQRcode ()<AVCaptureMetadataOutputObjectsDelegate>
{
    ScanQRcodev *_scanv;
    NSTimer *_timer;
    CGFloat _Dohight;
    BOOL    _hasR;
}

@end

@implementation DSSHScanQRcode

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.frame = [UIApplication sharedApplication].keyWindow.bounds;
    self.title = @"二维码/条码";
    [self.navigationController.navigationBar setBackgroundImage:[UnviersalTool createImageWithColor:[UIColor clearColor]]
                                                  forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage=[UnviersalTool createImageWithColor:[UIColor clearColor]];
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem * backBarBtn = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"fanhui"] style:UIBarButtonItemStylePlain target:self action:@selector(backBarBtnClick)];
    self.navigationItem.leftBarButtonItem = backBarBtn;
    [self createRoundV];
    [self createScanQRcodeV];
   
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"shake_sound_male" ofType:@"wav"];
    if (path) {
        //注册声音到系统
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path],&shake_sound_male_id);
       //AudioServicesPlaySystemSound(shake_sound_male_id);
        //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
    }
    // Do any additional setup after loading the view.
}
-(void)backBarBtnClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    if (self.session) {
        
        [self.session startRunning];
    }
    [self animation];
}


- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:YES];
    
    if (self.session) {
        
        [self.session stopRunning];
    }
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)animation{
    
    _timer = [NSTimer timerWithTimeInterval:0.03 target:self selector:@selector(ChangeFrame) userInfo:nil repeats:YES];
    
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    [_timer fire];
    
}
-(void)ChangeFrame
{
    _scanv.line.y += 3.0;
    if(_scanv.line.y >= SCANZ)
    {
        _scanv.line.y =0;
    }
}
-(void)createRoundV
{
    CGFloat ap = 0.5;
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ZYAppWidth, (ZYAppHeight-SCANZ)/2)];
    view1.backgroundColor = [UIColor grayColor];
    view1.alpha = ap;
    [self.view addSubview:view1];
    UIView *view2 =[[UIView alloc] initWithFrame:CGRectMake(0, view1.bounds.size.height + SCANZ, ZYAppWidth, (ZYAppHeight-SCANZ)/2)];
    view2.backgroundColor = [UIColor grayColor];
    view2.alpha = ap;
    [self.view addSubview:view2];
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(view1.frame), (ZYAppWidth-SCANZ)/2, ZYAppHeight-2*view1.bounds.size.height)];
    view3.backgroundColor = [UIColor grayColor];
    view3 .alpha = ap;
    [self.view addSubview:view3];
    UIView *view4 =[[UIView alloc] initWithFrame:CGRectMake(view3.bounds.size.width+SCANZ, CGRectGetMaxY(view1.frame), (ZYAppWidth-SCANZ)/2, ZYAppHeight-2*view1.bounds.size.height)];
    view4.backgroundColor = [UIColor grayColor];
    view4.alpha = ap;
    [self.view addSubview:view4];
    self.scansize = CGRectMake(CGRectGetMaxX(view3.frame), CGRectGetMaxY(view1.frame), SCANZ, SCANZ);
    _Dohight = view3.y;
    //创建扫描区域
    _scanv = [[NSBundle mainBundle] loadNibNamed:@"ScanQRcodeV" owner:nil options:nil][0];
    _scanv.frame = _scansize;
    _scanv.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_scanv];
    UILabel *lable =  [[UILabel alloc] init];
    lable.text = @"将二维码/条形码对准框内即可扫描";
    lable.textColor = [UIColor whiteColor];
    lable.font = FONT(12);
    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lable];
    [lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_scanv.mas_bottom).with.offset(10);
        make.height.equalTo(@15);
        make.centerX.equalTo(_scanv.mas_centerX);
        make.width.mas_equalTo(SCANZ);
    }];
    
}
-(void)createScanQRcodeV
{

    NSError *error = nil;
    //获取设备实例
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //创建输入流
    _videoInput = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error ];
    if(!_videoInput)
    {
        DSSHLog(@"%@", [error localizedDescription]);
        return;
    }
    

    //创建会话
    _session =[[AVCaptureSession alloc] init];
    
    _session.sessionPreset = AVCaptureSessionPreset1920x1080;
    [_session addInput:_videoInput];
    //创建数据输流

    _output = [[AVCaptureMetadataOutput alloc] init];
    
   [_output setRectOfInterest:CGRectMake(_scansize.origin.y / ZYAppHeight, _scansize.origin.x / ZYAppWidth, SCANZ/ZYAppWidth,  SCANZ/ZYAppWidth)];
    
    
    dispatch_queue_t queue;
    queue = dispatch_queue_create("KKKKK", nil);
    
    
    [_output setMetadataObjectsDelegate:self queue:queue];
    
    
    [_session addOutput:_output];
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    //创建输出对象
    _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_session];
    [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_previewLayer setFrame:[UIApplication sharedApplication].keyWindow.bounds];
    [self.view.layer insertSublayer:_previewLayer atIndex:0];
    
}
-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects
      fromConnection:(AVCaptureConnection *)connection
{
    if(_hasR){
        return;
    }
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        NSString *result;
        _hasR = YES;
        result = metadataObj.stringValue ;
         AudioServicesPlaySystemSound(shake_sound_male_id);
        [_timer invalidate];
        [_session stopRunning];
        [self performSelectorOnMainThread:@selector(reportScanResult:) withObject:result waitUntilDone:NO];
    }
}
-(void)reportScanResult:(id)sender //解析数据
{
    DSSHLog(@"%@",sender);
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
